package com.xiangyueEducation.uploaderCloud.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiangyueEducation.uploaderCloud.utils.Result;

import com.xiangyueEducation.uploaderCloud.constant.RegexConstant;
import com.xiangyueEducation.uploaderCloud.mapper.ModuleMapper;
import com.xiangyueEducation.uploaderCloud.mapper.QuestionResultMapper;
import com.xiangyueEducation.uploaderCloud.mapper.QuestionsMapper;
import com.xiangyueEducation.uploaderCloud.pojo.dto.AnsDTO;
import com.xiangyueEducation.uploaderCloud.pojo.entity.Modules;
import com.xiangyueEducation.uploaderCloud.pojo.entity.QuestionResult;
import com.xiangyueEducation.uploaderCloud.pojo.entity.Questions;
import com.xiangyueEducation.uploaderCloud.pojo.vo.DoTestVo;
import com.xiangyueEducation.uploaderCloud.service.QuestionService;
import com.xiangyueEducation.uploaderCloud.utils.enums.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    private QuestionsMapper questionsMapper;
    @Autowired
    private ModuleMapper moduleMapper;
    @Autowired
    private QuestionResultMapper questionResultMapper;

    @Override
    public void insertBatch(List<Questions> questions) {
        questionsMapper.insertBatch(questions);
    }

    @Override
    public List<Questions> queryByModuleId(Long moduleId) {
        QueryWrapper<Questions> questionsQueryWrapper = new QueryWrapper<>();
        questionsQueryWrapper.eq("test_id",moduleId);
        questionsQueryWrapper.orderByAsc("question_number");
        List<Questions> questions = questionsMapper.selectList(questionsQueryWrapper);
        //数据库中没数据，及时返回前端
        if (questions==null||questions.isEmpty()){
            return Collections.emptyList();
        }

        return questions;
    }

    @Override
    public Result checkQuestions(List<Questions> questions) {
        //检验传过来的moduleId是否合法，不可能查多次数据库，于是采用先去重，如果set大于1，直接返回，如果set等于1再去查看是否存在数据库中
        HashSet<Long> set = new HashSet<>();
        //存储非法测试题被启用序号(非主键id)的集合 写到一半不写了的那种
        List<Integer> invalidIds = new ArrayList<>();
        //存储不符合格式的集合
        List<Integer> formatValueIds = new ArrayList<>();
        List<Integer> formatOptionIds = new ArrayList<>();
        Integer number = 1;
        //存储不符合
        //set去重+检验
        for (Questions question : questions) {
            //如果题目是非法且被启用的题目
            if (question == null) {
                invalidIds.add(null);
                continue;
            }
            else if (question.isBlank()) {
                invalidIds.add(question.getQuestionNumber());
                continue;
            }
            //获取题目id，存入集合
            Long testId = question.getTestId();
            if (testId == null || testId <= 0) return Result.build(null, ResultCodeEnum.TEST_ID_ERROR);
            set.add(testId);
            //如果题目的长度和选项长度不一致
            String[] values = question.getVal().split(" ");
            String[] options = question.getOptions().split(" ");
            if (values.length != options.length) return Result.build(question, ResultCodeEnum.QUESTION_VAL_NOT_MATCH);
            //校验选项和价值是否符合规矩
            for (int i = 0; i < options.length; i++) {
                if(!ReUtil.isMatch(RegexConstant.OPTION,options[i])){
                    formatOptionIds.add(question.getQuestionNumber());
            }   try{
                    Double.parseDouble(values[i]);
                }catch (Exception e){
                    formatValueIds.add(question.getQuestionNumber());
                }
            }
            // 如果开启并且题目的序号不是自增的，不知道为什么，此处永远不真，后面加个非也不真
            if(!(question.getStatus()&&(question.getQuestionNumber().equals(number))))
            {return Result.build(question, ResultCodeEnum.QUESTION_NUMBER_SEQUENCE_ERROR);}
            System.out.println("number:"+number+",question:"+question.getQuestionNumber());
            number++;
        }
        //如果set集合中的元素不是1则说明这里面一定有不对的，直接返回前端
        if (set.size() != 1) {

            return Result.build(set, ResultCodeEnum.TEST_ID_ERROR);
        }
        //查数据库
        if (!invalidIds.isEmpty()) Result.build(invalidIds, ResultCodeEnum.INVALID_QUESTION_ARE_ENABLED);
        if (!formatValueIds.isEmpty()) Result.build(formatValueIds, ResultCodeEnum.FORMAT_VALUE_ERROR);
        if (!formatOptionIds.isEmpty()) Result.build(formatOptionIds, ResultCodeEnum.FORMAT_OPTION_ERROR);
        return null;
    }

    @Override
    @Transactional
    public void updateQuestion(List<Questions> questions) {
        Long testId = questions.get(0).getTestId();
        QueryWrapper<Questions> questionsQueryWrapper = new QueryWrapper<Questions>().eq("test_id", testId);
        questionsMapper.delete(questionsQueryWrapper);
        questionsMapper.insertBatch(questions);
    }

    @Override
    public Result doTest(AnsDTO quizDTO, Long userId, Modules modules) {
        //查题目
        Long testId = quizDTO.getTestId();
        //获取测试题
        QueryWrapper questionsQueryWrapper = new QueryWrapper<Questions>().eq("test_id",testId)
                                            .orderByAsc("question_number");
        List<Questions> questionsList = questionsMapper.selectList(questionsQueryWrapper);
        Double[] ans = quizDTO.getAns();
        //如果长度不同直接返回试题长度错误
        if (questionsList.size()!=ans.length)return Result.build(null, ResultCodeEnum.QUESTION_LENGTH_ERROR);
        //试题默认全是-1分，标记没做
        Double sum = 0.0;
        for (int i = 0; i < ans.length; i++) {
            if (ans[i]!=-1){
                sum+=ans[i];
            }
        }
        //四舍五入
        int total = (int) Math.round(sum);
        DoTestVo doTestVo = BeanUtil.copyProperties(modules, DoTestVo.class);
        doTestVo.setScore(total);
        LocalDateTime now = LocalDateTime.now();
        doTestVo.setFinishedTime(now);
        //将做题结果，存入数据库
        QuestionResult questionResult = new QuestionResult();
        questionResult.setScore(total);
        questionResult.setTestId(testId);
        questionResult.setStudentUserId(userId);
        questionResult.setCreateTime(now);
        questionResult.setUpdateTime(now);
        questionResultMapper.insert(questionResult);
        return Result.ok(doTestVo);
    }
}
